package com.ktmall.service.impl;

import com.ktmall.mapper.*;
import com.ktmall.pojo.*;
import com.ktmall.service.OrderService;
import com.ktmall.utils.CharUtils;
import com.ktmall.vo.CartItemVo;
import com.ktmall.vo.PreOrder;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单相关Service实现类
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CartItemMapper cartItemMapper;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private SkuItemMapper skuItemMapper;
    @Autowired
    private GoodsItemMapper goodsItemMapper;

    @Override
    @Transactional
    public int saveOrder(Order order) {
        String orderSn = CharUtils.getRandomString(6).toLowerCase() + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        order.setOrderSn(orderSn);
         orderMapper.saveOrder(order);
         List<Integer> ids = new ArrayList<>();
         int orderId = order.getId();
        if(order.getGoods() != null && !order.getGoods().isEmpty()){
            for (OrderDetail detail : order.getGoods()){
                ids.add(detail.getCartId());
                skuItemMapper.updateInventory(detail.getSkuId(),detail.getQuantity());
                detail.setOrderId(orderId);
                orderMapper.saveOrderDetail(detail);
            }
            //删除购物车中的商品
            cartItemMapper.batchDel(ids.toArray(new Integer[0]));
        }
        return orderId;
    }

    @Override
    public Order findById(Integer id) {
        Order o = orderMapper.findById(id);
        o.setAddress(addressMapper.findById(o.getAddressId()));
        List<OrderDetail> odList = orderMapper.findByOrderId(o.getId());
        odList = odList.stream().map((od) -> {
            SkuItem sku = skuItemMapper.findById(od.getSkuId());
            GoodsItem goods = goodsItemMapper.findById(sku.getGoodsId());
            sku.setGoods(goods);
            od.setSkuItem(sku);
            od.setCurPrice(new BigDecimal("0.9").multiply(sku.getPrice()).setScale(2));
            od.setName(goods.getGoodsName());
            od.setPicture(sku.getPicture());
            return od;
        }).collect(Collectors.toList());
        o.setGoods(odList);
        return o;
    }

    @Override
    public int getCount(Integer userId, Integer orderState) {
        return orderMapper.getCount(userId, orderState);
    }

    @Override
    public List<Order> getOrderListPage(Integer currentPageNo, Integer pageSize, Integer userId, Integer orderState) {
        Integer from = (currentPageNo - 1) * pageSize;
        List<Order> list = orderMapper.getOrderListPage(from,pageSize,userId,orderState);
        list.stream().map((o) -> {
            o.setAddress(addressMapper.findById(o.getAddressId()));
            List<OrderDetail> odList = orderMapper.findByOrderId(o.getId());
            odList = odList.stream().map((od) -> {
                SkuItem sku = skuItemMapper.findById(od.getSkuId());
                GoodsItem goods = goodsItemMapper.findById(sku.getGoodsId());
                sku.setGoods(goods);
                od.setSkuItem(sku);
                od.setCurPrice(new BigDecimal("0.9").multiply(sku.getPrice()).setScale(2));
                od.setName(goods.getGoodsName());
                od.setPicture(sku.getPicture());
                return od;
            }).collect(Collectors.toList());
            o.setGoods(odList);
            return o;
        }).collect(Collectors.toList());
        return list;
    }

    @Override
    public int updatePayStatus(Order orderInfo) {
        return orderMapper.updatePayStatus(orderInfo);
    }

    @Override
    public PreOrder buyAgain(Integer userId, Integer orderId) {
        // 获取默认地址
        AddressParams defaultAddress = addressMapper.getDefaultAddress(userId);
        //获取订单详情
        List<OrderDetail> orderDetails = orderMapper.getOrderDetail(orderId);
        List<CartItemVo> list = new ArrayList<>();
        //获取商品基本信息
        for (OrderDetail detail : orderDetails) {
            GoodsItem goodsItem = goodsItemMapper.findById(detail.getGoodsId());
            SkuItem skuItem = skuItemMapper.findById(detail.getSkuId());
            CartItemVo cartItemVo = new CartItemVo();
            cartItemVo.setGoodsId(goodsItem.getId());
            cartItemVo.setSkuId(skuItem.getId());
            cartItemVo.setName(goodsItem.getGoodsName());
            cartItemVo.setPicture(skuItem.getPicture());
            cartItemVo.setCount(detail.getQuantity());
            cartItemVo.setPrice(skuItem.getPrice());
            cartItemVo.setNowPrice(skuItem.getPrice().multiply(new BigDecimal("0.9")).setScale(2));
            cartItemVo.setStock(Integer.valueOf(skuItem.getInventory()+""));
            cartItemVo.setAttrsText(detail.getAttrsText());
            list.add(cartItemVo);
        }
        return new PreOrder(defaultAddress,list);
    }

    @Override
    public int takeGoods(Integer id) {
        return orderMapper.takeGoods(id);
    }

    @Override
    public int review(Integer id) {
        return orderMapper.review(id);
    }
}
